from rest_framework import permissions, viewsets
from rest_framework.decorators import action
from snippets.permissions import IsOwnerOrReadOnly
from .filters import SnippetFilter

from .serializers import *
from .paginations import *


class SnippetViewSet(viewsets.ModelViewSet):
    """
        片段功能
        retrieve:
            返回一个片段

        list:
            返回片段列表

        create:
            创建片段

        delete:
            删除片段

        partial_update:
            部分更新片段

        update:
            更新片段
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    filter_class = SnippetFilter
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    @action(detail=True)
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
        用户功能
        retrieve:
            返回一个用户

        list:
            返回用户列表

        create:
            创建用户

        delete:
            删除用户

        partial_update:
            部分更新用户

        update:
            修改用户
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

